<template>
  <div class="navbar-container"  :style="{ height: hideBackground ? '60px' : '400px' }">
    <el-affix :offset="0" class="affix-navbar">
      <el-menu
        :default-active="activeIndex"
        mode="horizontal"
        :ellipsis="false"
        @select="handleSelect"
        class="navbar-menu"
        :class="{ 'navbar-scrolled': isScrolled }"
      >
        <div class="menu-container">
          <el-menu-item index="0">
            <img
              style="width: 100px"
              src="/src/assets/images/duibiaologo.png"
              alt="duibiao logo"
            />
          </el-menu-item>
          <el-menu-item index="1" @click="goToHome">首页</el-menu-item>
          <!-- <el-menu-item index="3" @click="goToCampatyList">公司列表</el-menu-item> -->
          <el-menu-item index="4" @click="goToSalarys">薪资对比</el-menu-item>
          <el-menu-item index="5" @click="goToWorkplaceroast">职场吐槽</el-menu-item>
          <!-- <el-menu-item index="6" @click="goToFillInfo">职级对标</el-menu-item> -->
          <el-menu-item index="7" @click="goToJobList">一站求职</el-menu-item>

          <!-- 登录按钮或用户信息 -->
          <div style="flex-grow: 1;"></div>
          <div v-if="isLoggedIn" class="user-info">
            <el-dropdown @command="handleUserCommand">
              <span class="el-dropdown-link">
                <el-avatar v-if="avatarUrl" :size="36" :src="avatarUrl"></el-avatar>
                <el-avatar v-else :size="36">{{ username }}</el-avatar>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="editInfo">编辑信息</el-dropdown-item>
                  <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                  <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <el-menu-item v-else index="login" class="login-btn" @click="goToLogin">
            <div class="avatar-wrapper">
              <el-avatar :size="36">登</el-avatar>
            </div>
          </el-menu-item>
        </div>
      </el-menu>
    </el-affix>

        <!-- 背景图 -->
     
         <div class="navbar-bg" >
           <div class="navbar-title">
          
            
            <div class="btn-check-salary" @click="goToFillInfo">
              测一测
            </div>
          </div>
        </div>
    


  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted,onUnmounted,inject,watch  } from 'vue'
import { useRouter } from 'vue-router'
import { userApi } from '../utils/api'
import apiConfig from '../utils/apiConfig'

// 定义 props
const props = defineProps({
  showBackground: {
    type: Boolean,
    default: true
  }
})


// 注入全局状态
const globalState = inject('$globalState', { hideMenuBackground: false })

// 计算是否应该隐藏背景
const hideBackground = ref(false)

// 监听全局状态变化
const stopWatcher = globalState && typeof globalState === 'object' && 'hideMenuBackground' in globalState 
  ? watch(() => globalState.hideMenuBackground, (newValue) => {
      hideBackground.value = newValue
    }, { immediate: true })
  : null


const router = useRouter()
const activeIndex = ref('1')
const isLoggedIn = ref(false)
const username = ref('')
const avatarUrl = ref('')
const isScrolled = ref(false)

// 检查用户是否已登录
const checkLoginStatus = async () => {
  const token = localStorage.getItem('ACCESS_TOKEN')
  isLoggedIn.value = !!token
  
  // 可以从localStorage或通过API获取用户名
  if (token) {
    const savedUsername = localStorage.getItem('USERNAME');
    username.value = savedUsername || '用户'; // 如果没有保存用户名，则使用默认值'用户'
    
    // 获取用户信息，包括头像
    try {
      const response = await userApi.getUserInfo();
      const userInfo = response.data || response;
      if (userInfo && (userInfo.avatar_url || userInfo.avatarUrl)) {
        const avatar = userInfo.avatar_url || userInfo.avatarUrl;
        // 如果是绝对URL直接使用，否则加上基础路径
        if (avatar.startsWith('http')) {
          avatarUrl.value = avatar;
        } else {
          // 否则加上基础URL
          const baseUrl = apiConfig.imageBaseURL.development;
          // 处理路径中的重复斜杠
          if (avatar.startsWith('/')) {
            avatarUrl.value = baseUrl + avatar;
          } else {
            avatarUrl.value = baseUrl + '/' + avatar;
          }
        }
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
    }
  }
}

// 处理用户下拉菜单命令
const handleUserCommand = async (command) => {
  //  const userResponse = await userApi.getUserInfo();
  //  console.log(userResponse);
  if (command === 'logout') {
    try {
      // 调用登出API
      await userApi.logout()
    } catch (error) {
      console.error('登出API调用失败:', error)
    } finally {
      // 清除本地token
      localStorage.removeItem('ACCESS_TOKEN')
      // 更新登录状态
      isLoggedIn.value = false
      // 跳转到登录页
      router.push('/login')
    }
  } else if (command === 'profile') {
    // 跳转到个人中心页面（如果有的话）
    // router.push('/profile')
     router.push({
      name: 'PersonalCenter',
      query: {
        username: username.value
      }
    })
  }else if (command === 'editInfo') {
    // 跳转到个人中心页面（如果有的的话）
    // router.push('/profile')
     router.push({
      name: 'EditInfo',
      query: {
        username: username.value
      }
    })
  }
}

const handleSelect = (key: string, keyPath: string[]) => {
  if (key !== 'login') { // 排除登录按钮的select事件
    console.log(key, keyPath)
  }
}

const goToHome = () => {
  router.push('/') // 跳转到首页
}
const goToCampatyList = () => {
  router.push('/campatylist') // 跳转到首页
}
const goToSalarys = () => {
  router.push('/salarieslist') // 跳转到薪酬页
}

const goToWorkplaceroast = () => {
  router.push('/roastlist') // 跳转到吐槽页
}

const goToLogin = () => {
  router.push('/login') // 跳转到登录页
}

const goToFillInfo = () => {
  router.push('/tabs') // 跳转到信息添加页面
}
const goToJobList = () => {
  router.push('/joblist') // 跳转到信息添加页面
}

// 处理滚动事件
const handleScroll = () => {
  isScrolled.value = window.scrollY > 0
}

// 组件挂载时检查登录状态
onMounted(() => {
  checkLoginStatus()
  window.addEventListener('scroll', handleScroll)
})

// 监听路由变化，更新登录状态
router.afterEach(() => {
  checkLoginStatus()
})

// 在组件卸载前移除事件监听器
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
.navbar-container {
  width: 100%;
  position: relative;
  overflow: hidden;
  height: 400px;
  background-color: #ffffff;
}

.affix-navbar {
  width: 100%;
  z-index: 1000;
}

.navbar-menu.navbar-scrolled {
  background-color: rgba(255, 255, 255, 0.95) !important;
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.all-container { 
  /* max-width: 1200px; */
  background-color: #003366;
  margin: 0 auto;
  display: flex;
  align-items: center;
  width: 100%;
  height: 600px;
 
}

.navbar-bg {
  /* position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: -1; */
  width: 100%;
  height: 360px;
  /* border: 1px solid #ccc; */

  /* 核心背景设置 */
  background-image: url('../assets/images/banner.png');
  /* background-size: 450px 300px;  */
  background-position:center center; 
  background-repeat: no-repeat; /* 禁止重复，只显示一张 */
  /* margin-top: 10%; */
      background-color: #0055c1;
      
}


.navbar-title{
  width: 1200px;
    position: relative;
   
    margin: 0 auto;
}




 /* 顶部标题样式 */
        .navbar-title h2 {
            color: #F95244; /* 红色标题 */
            font-size: 48px;
            font-weight: 500;
            margin-bottom: 20px;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            line-height: 1.3;
            font-style: italic;
        }
        
        /* 说明文字样式 */
        .navbar-title-text {
            color: white;
            font-size: 30px;
            text-align: center;
            line-height: 1.6;
            font-weight: 500;
            font-style: italic;
        }
        
        /* 按钮样式 */
        .btn-check-salary {
            background-color: #003366; /* 深蓝色按钮背景 */
            color: #FFD700; /* 黄色文字 */
            padding: 15px 30px;
            border-radius: 20px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            display: inline-block;
            transition: all 0.3s ease;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
            border: none;
            width: auto;
            max-width: 300px;
            margin: 0 auto;
            margin-left: 200px;
            margin-top: 30px;
            position: absolute;
            top: 220px;
            left: 90px;
            
        }
        
        .btn-check-salary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.25);
            background-color: #002244;
        }
        
        .btn-check-salary:active {
            transform: translateY(1px);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }
        


.navbar-menu {
  /* background-color: transparent !important; */
  border-bottom: none;
  box-shadow: none;
  transition: all 0.3s ease;
}

.menu-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0 20px;
  height: 60px; /* 增加高度 */
  justify-content: space-between;
}

/* 菜单项样式 */
.el-menu-item {
  margin: 0 15px;
  color: rgb(0, 0, 0);
  font-size: 16px; /* 增大字体 */
  /* font-weight: 600; */
  border-bottom: none
}

 .el-menu--horizontal.el-menu {
    border-bottom: none;
}

.el-menu-item:hover {
  background-color: transparent !important;
  color: #2d63d8;
}

.el-menu--horizontal > .el-menu-item:nth-child(1) {
  margin-right: auto;
} 

.login-btn {
  padding: 0 12px !important;
  margin-left: 10px;
}

.login-btn:hover,
.login-btn:focus {
  background-color: transparent !important;
}

.avatar-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
}

.el-avatar {
  background-color: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: none;
}

.user-info {
  padding: 0 12px;
  display: flex;
  align-items: center;
  height: 100%;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
}

/* 禁用默认 hover 效果 */
:deep(.login-btn .el-menu-item) {
  background-color: transparent !important;
}

:deep(.login-btn .el-menu-item:hover) {
  background-color: transparent !important;
}
</style>